<template>
  <div>
    <main class="editor shadow">
      <div id="editor"></div>
      <!-- <div :ref="editorElem"></div> -->
      <section class="actions">
        <a-button type="primary" @click="showModal">{{
          sumbitButtonMessage
        }}</a-button>
        <a-button danger>清空</a-button>
      </section>
    </main>
    <c-modal ref="modal" @submit="submit"></c-modal>
  </div>
</template>
<script>
// import xss from "xss";
import { onMounted, ref, defineComponent } from "vue";
import { useEditor } from "@u/editor.js";
import { useLocalStorage } from "@u/local-storage.js";
import { useDebounce } from "@u/common.js";
import { useSuccessNotice, useErrorNotice, useInfoNotice } from "@u/notice.js";
import CModal from "@b/modal.vue";
import http, { lazyRequest } from "@u/http.js";
import { useRoutePathToPage } from "@u/router.js";
import { useRouteQuery } from "@u/route";

export default defineComponent({
  name: "Editor",
  components: {
    CModal,
  },
  setup() {
    const modal = ref(null);
    const [draft] = useLocalStorage("draft");
    const toArticlePage = useRoutePathToPage(`articles/1`);
    let editor;
    onMounted(() => {
      editor = useEditor();
      // 设置editor的层级
      editor.config.zIndex = 0;
      // 设置editor的样式
      editor.config.height = 600;
      editor.create();
      editor.txt.html(draft.value);
      // 处理防抖--防抖--
      editor.config.onchange = useDebounce((newHtml) => {
        draft.value = newHtml;
        // TODO 下方代码展示不需要
        // draft.value = xss(newHtml);
        // useInfoNotice(
        //   {
        //     message: "草稿",
        //     description: "已缓存到本地",
        //   },
        //   3000
        // );
      });
    });
    let submit = async (record) => {
      modal.value.onButtonProps.loading = true;
      try {
        const request = http.post("/articles", {
          ...record,
          content: editor.txt.html(),
        });
        await lazyRequest(request);
        useSuccessNotice({
          message: "发布成功",
        });
      } catch (error) {
        useErrorNotice({
          message: "发布失败",
          description: error.reason || "未知错误",
        });
      } finally {
        modal.value.setVisible(false);
        modal.value.onButtonProps.loading = false;
        toArticlePage();
      }
    };
    const showModal = () => modal.value.setVisible(true);

    const id = useRouteQuery("id");
    const updateFlag = Boolean(id);
    const sumbitButtonMessage = updateFlag ? "更新" : "发布";
    console.log(updateFlag);
    if (updateFlag) {
      onMounted(async () => {
        try {
          const { data } = await http.get(`/articles/${id}`);
          editor.txt.html(data.content);
          modal.value.formRecord.title = data.title;
          modal.value.formRecord.synopsis = data.synopsis;
          modal.value.formRecord.type = data.type;
        } catch (error) {
          useInfoNotice({
            message: "文章获取失败",
            description: error.data || error.reason || "未知错误",
          });
        }
      });
      // 如果是更新操作，重写submit方法 后面的操作都是一样的
      submit = async (record) => {
        modal.value.onButtonProps.loading = true;
        try {
          modal.value.onButtonProps.loading = true;
          const request = http.put(`/articles/${id}`, {
            ...record,
            content: editor.txt.html(),
          });
          await lazyRequest(request);
          useSuccessNotice({
            message: "更新成功",
          });
          toArticlePage();
        } catch (error) {
          useErrorNotice({
            message: "更新失败",
            description: error.reason || "未知错误",
          });
        } finally {
          modal.value.setVisible(false);
          modal.value.onButtonProps.loading = false;
        }
      };
    }

    console.log(submit);

    return {
      showModal,
      modal,
      submit,
      sumbitButtonMessage,
    };
  },
});
</script>
<style scoped>
.editor {
  margin: 30px 10px;
  background-color: #eceff1;
  padding: 10px;
  border-radius: 4px;
}

.actions {
  padding: 8px;
  text-align: center;
}

.actions > * {
  margin: 10px;
}
</style>